package com.jt.www.job.agree;

import com.jt.www.dao.mapper.agree.AgreeManageEntityMapper;
import com.jt.www.util.DateUtils;
import com.jt.www.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 检查协议管理定时任务
 *
 * @author admin_ltf
 * @create 2019-04-13 15:51
 */
@Component
@EnableScheduling
public class CheckAgreeExpireTask implements SchedulingConfigurer {

    public static final Logger log = LoggerFactory.getLogger(CheckAgreeExpireTask.class);
    /**
     * 协议缓存key
     */
    private static final String AGREE_LOCK_KEY = "EDU_AGREE";
    @Autowired
    AgreeManageEntityMapper agreeManageEntityMapper;
    /**
     * 任务开关
     */
    @Value("${jtpf.agree.open}")
    private int checkOpen;
    /**
     * 任务执行周期
     */
    @Value("${jtpf.agree.cron}")
    private String cron;// 每天零点更新

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        if (checkOpen != 1) {
            return;
        }
        if (RedisUtil.setOneHoursLock(AGREE_LOCK_KEY)) {
            Runnable task0 = () -> checkStart();
            Trigger trigger0 = triggerContext -> new CronTrigger(cron).nextExecutionTime(triggerContext);
            taskRegistrar.addTriggerTask(task0, trigger0);
        }
    }

    private void checkStart() {

        // 检查 到现在为止  到期的协议  根据时间查询  调用协议的mapper  直接写sql ，返回一个list 即可  每天0点执行。

        String currentTime = DateUtils.getCurrentTime();
        List<String> resultList = agreeManageEntityMapper.selectByAgreetime(currentTime);
        if (resultList != null && resultList.size() > 0) {

            // 修改状态
            Integer num = agreeManageEntityMapper.updateStatusByOrderNos(resultList);
        }
    }

}
